package indi.kane.simpleproject.controller;

import com.alibaba.fastjson.JSON;
import indi.kane.simpleproject.entity.Account;
import indi.kane.simpleproject.service.impl.AccountService;
import indi.kane.simpleproject.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ResultVo login(HttpServletResponse httpServletResponse,
                          @RequestParam(value = "name") String name,
                          @RequestParam(value = "password") String password) {
        Account account = accountService.login(name, password);
        if(account != null) {
            Cookie cookie = new Cookie("logUser",account.getId().toString());
            cookie.setMaxAge(60);
            cookie.setPath("/");
            httpServletResponse.addCookie(cookie);
            return ResultVo.success(account);
        }
        else {
            return ResultVo.failed("用户名或密码错误");
        }
    }

    @RequestMapping("get/{id}")
    public String get(@PathVariable long id) {
        Account account = accountService.selectByPrimaryKey(id);
        return JSON.toJSONString(account);
    }

    @RequestMapping(value = "user", method = RequestMethod.POST)
    public ResultVo currentUser(@CookieValue(value = "logUser", required = false) String userId){
        if(userId !=null) {
            return ResultVo.success(userId);
        }
        else{
            return ResultVo.failed("尚无登录用户");
        }
    }

    @RequestMapping("insert")
    public ResultVo insert(@RequestBody Account account) {
        try {
            int isSuccess = accountService.insertSelective(account);
            if (isSuccess > 0) {
                return ResultVo.success("新增成功");
            } else {
                return ResultVo.failed("新增失败");
            }
        } catch (Exception ex) {
            return ResultVo.failed_exception("新增失败");
        }
    }
}
